<?php

namespace Modules\Shop\Api;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Shop\Entities\Goods;
use Modules\Shop\Transformers\GoodsResource;

/**
 * 搜索
 * @package Modules\Shop\Api
 */
class SearchController extends Controller
{
    /**
     * 商品搜索
     * @param Request $request
     * @return string|array|null
     */
    public function goods(Request $request)
    {
        $pageLimit = 10;
        $params = [
            'index' => 'edugoods',
            'body'  => [
                'query' => [
                    'multi_match' => [
                        "query" => $request->query('w'),
                        'fields' => ['title', 'content']
                    ]
                ],
                "from" => $request->input('page', 0) * $pageLimit,
                "size" => $pageLimit
            ]
        ];

        $result = app('es')->search($params)['hits']['hits'];
        $ids = collect($result)->pluck('_id');

        $goods = Goods::whereIn('id', $ids)->get();
        return GoodsResource::collection($goods);
    }
}
